#include "warninglogmodel.h"
#include "qdebug.h"
#include "robotlist.h"
#include <QDateTime>
#include "databasemanager.h"
WarningLogModel * WarningLogModel::m_pInstance = NULL;

WarningLogModel::WarningLogModel(QObject *parent)
    : QAbstractListModel{parent}
{
    initData();
}

WarningLogModel *WarningLogModel::getInstance()
{
    if(m_pInstance == NULL)
        m_pInstance = new WarningLogModel();
    return m_pInstance;
}

void WarningLogModel::initData()
{
    QList<WarningInfo> warningList =  DatabaseManager::getInstance()->getWarnings();
    beginInsertRows(QModelIndex(), m_data.size(), m_data.size());
    for(int i=0;i<warningList.length();i++)
    {
        m_data.append(warningList[i]);
    }
    endInsertRows();
}

int WarningLogModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;
    return m_data.size();
}

QVariant WarningLogModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() >= m_data.size() || index.row() < 0)
        return QVariant();
    const WarningInfo &info = m_data.at(index.row());
    switch (role) {
    case RobotRole:
        return info.robotName;
    case TimeRole:
        return info.warningTime;
    case LogRole:
        return info.warningText;
    default:
        return QVariant();
    }
}

QHash<int, QByteArray> WarningLogModel::roleNames() const
{
    QHash<int, QByteArray> roles;
    roles[TimeRole] = "time";
    roles[RobotRole]= "robot";
    roles[LogRole]  = "log";
    return roles;
}

void WarningLogModel::addData(QString strlog)
{
    Robot * robot=  RobotList::getInstance()->getCurRobot();
    QString strRobotName=tr("未获取到机器人");
    if(robot)
        strRobotName=robot->strName();
    qDebug()<<"[告警]"<<"机器人：["+strRobotName+"]"<<strlog;
    QString warningTime=QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    DatabaseManager::getInstance()->addWarning(strRobotName,warningTime, strlog);  //写数据库
    beginInsertRows(QModelIndex(), m_data.size(), m_data.size());
    m_data.append({strRobotName,warningTime, strlog});
    endInsertRows();
}

void WarningLogModel::deleteDatas()
{
    beginResetModel();
    m_data.clear();
    DatabaseManager::getInstance()->deleteWarning();
    endResetModel();
}
